import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Form, Input, Button, Spin, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { MusicInfoDetail, getMusicInfoPage } from '@/services/MusicInfoService';
import { famousPersonId } from '@/services/index';
import styles from './index.less';

const MusicList: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<MusicInfoDetail[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [hasMore, setHasMore] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const loadingRef = useRef(false);

  const getDefaultCover = (name: string) => {
    const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'];
    const index = name.length % colors.length;
    return (
      <div className={styles.defaultCover} style={{ backgroundColor: colors[index] }}>
        {name.slice(0, 2)}
      </div>
    );
  };

  // 获取数据
  const fetchData = async (values: any, page: number = 1, append: boolean = false) => {
    if (loadingRef.current) return;
    loadingRef.current = true;
    
    try {
      setLoading(true);
      const pageSize = 50;
      const response = await getMusicInfoPage({
        ...values,
        pageCurrent: page,
        pageSize,
        famousPersonId: famousPersonId
      });

      if (response) {
        const { list, totalCount } = response;
        setTotal(totalCount);
        setHasMore(totalCount > page * pageSize);
        
        if (append) {
          setData(prev => [...prev, ...list]);
          setCurrentPage(page);
        } else {
          setData(list);
          setCurrentPage(1);
        }
        
        if (!append) {
          containerRef.current?.scrollTo(0, 0);
        }
      }
    } catch (error) {
      message.error('获取音乐列表失败');
    } finally {
      setLoading(false);
      loadingRef.current = false;
    }
  };

  // 处理搜索
  const handleSearch = (values: any) => {
    fetchData(values);
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    fetchData({});
  };

  // 处理滚动加载
  const handleScroll = useCallback(() => {
    if (!containerRef.current || loading || !hasMore || loadingRef.current) return;

    const container = containerRef.current;
    const { scrollTop, clientHeight, scrollHeight } = container;
    const scrollThreshold = 100; // 滚动阈值

    // 检查是否滚动到底部
    if (scrollHeight - scrollTop - clientHeight < scrollThreshold) {
      const values = form.getFieldsValue();
      fetchData(values, currentPage + 1, true);
    }
  }, [loading, hasMore, currentPage, form]);

  // 监听滚动事件
  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, [handleScroll]);

  // 初始加载
  useEffect(() => {
    fetchData({});
  }, []);

  // 处理卡片点击
  const handleCardClick = (id: number) => {
    history.push(`/works/music/${btoa(id.toString())}`);
  };

  return (
    <div className={styles.musicListContent}>
      <div className={styles.searchSection}>
        <Form
          form={form}
          onFinish={handleSearch}
          className={styles.searchForm}
        >
          <Form.Item name="keyword">
            <Input
              placeholder="搜索音乐名称、专辑、简介..."
              allowClear
              size="middle"
              prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
            />
          </Form.Item>
          <div className="button-group">
            <Button type="primary" htmlType="submit" size="middle">搜索</Button>
            <Button onClick={handleReset} size="middle">重置</Button>
          </div>
        </Form>
        <div className={styles.searchResult}>
          找到 <span>{total}</span> 首音乐作品
        </div>
      </div>

      <div className={styles.musicListWrapper} ref={containerRef}>
        <div className={styles.musicList}>
          {data.map((item) => (
            <div
              key={item.id}
              className={styles.musicCard}
              onClick={() => item.id && handleCardClick(item.id)}
            >
              <div className={styles.coverWrapper}>
                {item.cover ? (
                  <img
                    src={`/api/file/play/${item.cover.id}`}
                    alt={item.name}
                    className={styles.cover}
                  />
                ) : getDefaultCover(item.name)}
              </div>
              <div className={styles.contentWrapper}>
                <div className={styles.header}>
                  <h3 className={styles.title}>{item.name}</h3>
                </div>
                <div className={styles.infoList}>
                  <div className={styles.infoItem}>
                    {item.releaseDate || '未知'}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
        
        {loading && (
          <div className={styles.loadingMore}>
            <Spin />
            <span>加载中...</span>
          </div>
        )}
        
        {!hasMore && data.length > 0 && (
          <div className={styles.noMore}>
            没有更多数据了
          </div>
        )}
      </div>
    </div>
  );
};

export default MusicList; 